import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useReturnStore = defineStore('return', () => {
  const selectedParts = ref([])
  const regionDict = ref([])
  const returnForm = ref({
    returnMethod: 'onsite',
    returnType: '旧件',
    parts: [],
  })
  const selecteAddressType = ref(true)
//设置地址是否可以被选择
  const setAddressType = (type: boolean) => {
    selecteAddressType.value = type
  }
  //获取地址是否可以被选择
  const getAddressType = () => {
    return selecteAddressType.value
  }

  const addPart = (part) => {
    const existingPart = selectedParts.value.find((p) => p.id === part.id)
    if (existingPart) {
      existingPart.quantity += part.quantity
    } else {
      selectedParts.value.push(part)
    }
  }
  const removePart = (partId: string) => {
    selectedParts.value = selectedParts.value.filter((p) => p.id !== partId)
  }

  const updatePartQuantity = (partId: string, quantity: number) => {
    const part = selectedParts.value.find((p) => p.id === partId)
    if (part) {
      part.quantity = quantity
    }
  }

  const setReturnMethod = (method: 'onsite' | 'express') => {
    returnForm.value.returnMethod = method
  }

  const setAddress = (address: any) => {
    returnForm.value.address = address
  }
  //设置地址字典
  const setRegionDict = (detail:any) => {
    regionDict.value = detail
  }
  //获取地址字典

  const setTrackingNumber = (number: string) => {
    returnForm.value.trackingNumber = number
  }
  const getRegionDictionary = () => {
    return regionDict.value
  }
  return {
    selectedParts,
    returnForm,
    setAddressType,
    getAddressType,
    addPart,
    setRegionDict,
    getRegionDictory: getRegionDictionary,
    removePart,
    updatePartQuantity,
    setReturnMethod,
    setAddress,
    setTrackingNumber,
  }
})
